package net.chasing.androidbaseconfig.util;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.KeyguardManager;
import android.app.UiModeManager;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.media.AudioManager;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.PowerManager;
import android.os.Vibrator;
import android.provider.Settings;
import android.view.Surface;
import android.view.Window;
import android.view.WindowManager;

import androidx.annotation.NonNull;

import net.chasing.androidbaseconfig.R;

public class SystemUtils {

    // region 亮度

    /**
     * 获取最大亮度，部分手机厂商修改了该值，所以不一定是255了
     */
    private static int getBrightnessMax() {
        try {
            Resources system = Resources.getSystem();
            int resId = system.getIdentifier("config_screenBrightnessSettingMaximum", "integer", "android");
            if (resId != 0) {
                return system.getInteger(resId);
            }
        } catch (Exception ignore) {

        }
        return 255;
    }

    /**
     * 获取屏幕亮度
     */
    public static float getScreenBrightness(@NonNull Activity activity) {
        ContentResolver contentResolver = activity.getContentResolver();
        int defVal = 125;
        return Settings.System.getInt(contentResolver,
                Settings.System.SCREEN_BRIGHTNESS, defVal) / (float) getBrightnessMax();
    }

    /**
     * 获取当前Activity设置的亮度
     */
    public static float getActivityBrightness(@NonNull Activity activity) {
        float brightness = activity.getWindow().getAttributes().screenBrightness;
        if (brightness == -1) {
            brightness = getScreenBrightness(activity);
        }
        return brightness;
    }

    /**
     * 设置屏幕亮度(0-1)   0以下则使用系统原本亮度
     *
     * @param lightPercent 0.0-1.0f
     */
    public static void setBrightness(@NonNull Activity activity, float lightPercent) {
        Window window = activity.getWindow();
        WindowManager.LayoutParams lpa = window.getAttributes();
        lpa.screenBrightness = lightPercent;
        if (lpa.screenBrightness > 1.0f)
            lpa.screenBrightness = 1.0f;
        window.setAttributes(lpa);
    }
    // endregion

    // region 声音
    //获取音量
    public static int getVolume(@NonNull Activity activity) {
        AudioManager audioManager = (AudioManager) activity.getSystemService(Context.AUDIO_SERVICE);
        return audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
    }

    //获取最大音量
    public static int getMaxVolume(@NonNull Activity activity) {
        AudioManager audioManager = (AudioManager) activity.getSystemService(Context.AUDIO_SERVICE);
        return audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
    }

    //设置音量
    public static void setVolume(@NonNull Activity activity, int volume) {
        AudioManager audioManager = (AudioManager) activity.getSystemService(Context.AUDIO_SERVICE);
        audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, volume, 0);
    }

    //判断是否处于静音状态
    public static boolean isVolumeMute(@NonNull Context context) {
        AudioManager audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
        return audioManager.getStreamVolume(AudioManager.STREAM_MUSIC) == 0;
    }

    private static long PRE_PLAY_RINGTONE_TIME;

    // 播放系统通知铃声
    public static void playRingtone(Context context) {
        long curTime = System.currentTimeMillis();
        if (curTime - PRE_PLAY_RINGTONE_TIME <= 1000) return;
        PRE_PLAY_RINGTONE_TIME = curTime;
        try {
            Ringtone ringtone = RingtoneManager.getRingtone(context, RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION));
            ringtone.play();
        } catch (Exception ignored) {
        }
    }
    // endregion

    // region 震动
    private static Vibrator vibrator;

    /**
     * 简单的震动
     *
     * @param context 调用震动类的 context
     */
    @SuppressWarnings("static-access")
    public static void vibrator(Context context) {
        if (vibrator == null)
            vibrator = (Vibrator) context.getApplicationContext().getSystemService(context.VIBRATOR_SERVICE);
        vibrator.vibrate(50);
    }

    /**
     * 简单的震动
     *
     * @param context      调用震动类的 context
     * @param milliseconds 震动的时间
     */
    @SuppressWarnings("static-access")
    public static void vibrator(Context context, int milliseconds) {
        if (vibrator == null)
            vibrator = (Vibrator) context.getApplicationContext().getSystemService(context.VIBRATOR_SERVICE);
        vibrator.vibrate(milliseconds);
    }

    /**
     * 复杂的震动
     *
     * @param context 调用复杂震动的context
     * @param pattern 震动的形式
     * @param repeat  震动循环的次数
     **/
    @SuppressWarnings("static-access")
    public static void vibrator(Context context, long[] pattern, int repeat) {
        if (vibrator == null)
            vibrator = (Vibrator) context.getApplicationContext().getSystemService(context.VIBRATOR_SERVICE);
        vibrator.vibrate(pattern, repeat);
    }

    public static void stop() {
        if (vibrator != null)
            vibrator.cancel();
    }
    // endregion

    /**
     * 屏幕是否黑屏（完全变黑那种，屏幕变暗不算）
     *
     * @param context 上下文
     * @return 屏幕变黑，则返回true；屏幕变亮，则返回false
     */
    public static boolean isScreenOff(Context context) {
        KeyguardManager manager = (KeyguardManager) context.getSystemService(Context.KEYGUARD_SERVICE);
        return manager.inKeyguardRestrictedInputMode();
    }

    /**
     * 判断app是否处于深色模式
     */
    public static boolean isAppNightMode(Context context) {
        UiModeManager uiModeManager = (UiModeManager) context.getSystemService(Context.UI_MODE_SERVICE);
        int uiMode = context.getResources().getConfiguration().uiMode;
        return (uiMode & Configuration.UI_MODE_NIGHT_MASK) == Configuration.UI_MODE_NIGHT_YES;
    }

    /**
     * 判断系统是否处于深色模式
     */
    public static boolean isSystemNightMode(Context context) {
        UiModeManager uiModeManager = (UiModeManager) context.getSystemService(Context.UI_MODE_SERVICE);
        return uiModeManager.getNightMode() == UiModeManager.MODE_NIGHT_YES;
    }

    /**
     * 忽略电池优化
     */
    public static void ignoreBatteryOptimization(Activity activity) {
        PowerManager powerManager = (PowerManager) activity.getSystemService(Context.POWER_SERVICE);
        boolean hasIgnored;
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {
            hasIgnored = powerManager.isIgnoringBatteryOptimizations(activity.getPackageName());
            //  判断当前APP是否有加入电池优化的白名单，如果没有，弹出加入电池优化的白名单的设置对话框。
            if (!hasIgnored) {
                @SuppressLint("BatteryLife") Intent intent = new Intent(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS);
                intent.setData(Uri.parse("package:" + activity.getPackageName()));
                activity.startActivity(intent);
            } else
                ToastUtils.showShort(activity, R.string.base_is_keeping_in_active_state);
        }
    }

    /**
     * 判断手机是否横屏
     */
    public static boolean isHorizontalScreen(Activity activity) {
        int angle = ((WindowManager) activity.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay().getRotation();
        //如果屏幕旋转90°或者270°是判断为横屏，横屏规避不展示
        return angle == Surface.ROTATION_90 || angle == Surface.ROTATION_270;
    }

    // region 检测应用是否安装
    public static boolean isNotInstallWechat(Context context) {
        return !isInstall(context, "com.tencent.mm");
    }

    public static boolean isInstallGaoDe(Context context) {
        return isInstall(context, "com.autonavi.minimap");
    }

    /**
     * 判断安装的应用
     *
     * @param packageName 应用包名
     */
    private static boolean isInstall(Context context, String packageName) {
        PackageInfo packageInfo;
        try {
            packageInfo = context.getPackageManager().getPackageInfo(packageName, 0);
        } catch (PackageManager.NameNotFoundException e) {
            packageInfo = null;
        }
        return packageInfo != null;
    }
    // endregion
}
